class BundlingsController < AuthorizedController
  
  # Create a new link between the current bundle and the desired posting
  def create
    @bundling = current_user.bundlings.find_by_bundle_id_and_posting_id(session[:active_bundle_id], params[:posting_id])
    @bundling = current_user.bundlings.build(:bundle_id => session[:active_bundle_id], :posting_id => params[:posting_id]) unless @bundling
    @bundling.current = true
    
    if @bundling.save
      @current_bundlings = current_user.bundlings.find_all_by_current_and_bundle_id(true, session[:active_bundle_id], :order => 'bundlings.updated_at')
      respond_to do |wants|
        wants.json { render :json => { 
          :dom_id => dom_id(@bundling),
          :content => render_to_string(:partial => 'bundling.html.erb', :collection => @current_bundlings)
        }}
      end
    else
      head 500
    end
  end

  # Expire the bundling for this [:user, :bundle, :posting] set
  def destroy
    @bundling = current_user.bundlings.find_by_id(params[:id])
    head 500 and return unless @bundling
    
    @bundling.toggle!(:current) if @bundling.current?
    if @bundling.current?
      head 500
    else
      @current_bundlings = current_user.bundlings.find_all_by_current_and_bundle_id(true, @bundling.bundle_id, :order => 'bundlings.updated_at')
      respond_to do |wants|
        wants.json { render :json => {
          :dom_id => dom_id(@bundling),
          :content => render_to_string(:partial => 'bundling.html.erb', :collection => @current_bundlings)
        }}
      end
    end
  end
end
